<template>
  <div id="app"></div>
</template>

<script>
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

import 'mapbox-gl-controls/lib/controls.css';
import axios from 'axios';

import geojsonvt from 'geojson-vt';

export default {
  data() {
    return {
      // 历史数据
      historyData: null,
      // map 地图对象实例
      map: null,
    };
  },
  beforeCreate() {
    // 兼容旧版本没有remove()的情况
    if (!('remove' in Element.prototype)) {
      Element.prototype.remove = function () {
        if (this.parentNode) {
          this.parentNode.removeChild(this);
        }
      };
    }
  },
  mounted() {
    this._createBaseMap();
  },
  methods: {
    _createBaseMap() {
      mapboxgl.accessToken =
        'pk.eyJ1IjoiaW54bG54IiwiYSI6ImNsMzRmZDE4dTBhOWczaWs3a2psanphMnUifQ.iKIlYhNlW_13OqBJLOc9sw';

      const map = new mapboxgl.Map({
        container: 'app',
        //自己绘制的样式地图令牌
        antialias: true, //抗锯齿
        style: 'mapbox://styles/mapbox/dark-v10',
        center: [113.97923191113188, 22.589860256941634],
        // center: [ -16.06102635228848,  84.93125123478856],
        zoom: 11.5,
      });

      this.map = map;
      window.map = map;

      // function metersToPixelsAtMaxZoom(meters, latitude) {
      //   return meters / 0.075 / Math.cos((latitude * Math.PI) / 180);
      // }

      const typeMap = new Map([
        [
          'fill',
          {
            'fill-color': 'yellow',
            'fill-outline-color': 'red',
          },
        ],
        [
          'circle',
          {
            'circle-radius': 10,
            // 'circle-radius': {
            //   stops: [
            //     [0, 0],
            //     [20, _pixelRadius],
            //   ],
            //   base: 2,
            // },
            // Color circle by earthquake magnitude  用颜色标出 PM2.5 的污染程度
            'circle-color': 'skyblue',
            'circle-stroke-color': 'transparent',
            'circle-stroke-width': 0, // 圆点的边框大小
          },
        ],
      ]);

      map.on('load', function () {
        const size = '50';
        const startTime = '2022-06-15 00:00:00';
        const endTime = '2022-06-15 23:00:00';
        // 添加矢量切片数据源
        // map.addSource('custom-vector-source', {
        //   type: 'vector',
        //   tileSize: 512,
        //   tiles: [
        //     // 'http://192.168.101.147:8081/tiles/{z}/{x}/{y}',
        //     // 'http://192.168.101.147:9080/pg_postgis_mvt/api/v1/{z}/{x}/{y}',
        //     // `http://192.168.101.147:8088/tile/${size}/${1}/${startTime}/${endTime}/{z}/{x}/{y}`,
        //     // 'http://192.168.101.147:8081/tile1?t=vt&z={z}&x={x}&y={y}',
        //     // 'https://tiles-a.basemaps.cartocdn.com/vectortiles/carto.streets/v1/{z}/{x}/{y}.mvt',
        //     'http://192.168.101.147:8081/tile/{z}/{x}/{y}',
        //   ],
        // });

        axios
          .get(
            `http://192.168.101.153:10060/history/GJson/${size}/1/${startTime}/${endTime}`
          )
          .then((r) => {
            const { data } = r;
            console.log('data :>> ', data);
            const geoInitTemplate = {
              type: 'FeatureCollection',
              features: [
                // {
                //   type: 'Feature',
                //   geometry: {
                //     type: 'Polygon',
                //     coordinates: [],
                //   },
                // },
              ],
            };

            const type = 'fill';
            geoInitTemplate.features = data;
            const tileIndex = geojsonvt(geoInitTemplate);
            const coords = tileIndex.tileCoords;
            const features = tileIndex.getTile(
              coords[0].z,
              coords[0].x,
              coords[0].y
            );

            console.log('features :>> ', features);
            map.addSource('geoSource', {
              type: 'geojson',
              data: {
                type: 'FeatureCollection',
                features,
              },
            });

            // // 添加矢量切片数据源;
            // map.addSource('custom-vector-source', {
            //   type: 'vector',
            //   tiles: Array.from(tiles),
            // });

            map.addLayer({
              id: 'geoLayer',
              source: 'geoSource',
              type,
              paint: typeMap.get(type),
            });
            // map.addLayer({
            //   id: 'vectorLayer',
            //   source: 'custom-vector-source',
            //   type,
            //   paint: typeMap.get(type),
            // });
          });

        // 添加图层
        // map.addLayer({
        //   id: 'custom-vector-tile-layer',
        //   type,
        //   source: 'custom-vector-source1',
        //   'source-layer': 'points',
        //   paint: typeMap.get(type),
        // });
      });

      // zoom变化时打印zoom值
      map.on('zoom', function (e) {
        console.log('zoom :>> ', e.target.getZoom());
      });

      map.on('click', 'boundary-layer', function (e) {
        // console.log('click :>> ', e);
        const features = map.queryRenderedFeatures(e.point, {
          layers: ['boundary-layer'],
        });
        console.log('features :>> ', features);
      });
    },
  },
};
</script>

<style>
body {
  padding: 0;
  margin: 0;
  overflow: hidden;
}
#app {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
}

/* 将底部的logo和信息声明隐藏 */
.mapboxgl-ctrl-logo {
  display: none !important;
}
.mapboxgl-ctrl-bottom-right {
  display: none !important;
}

/* 弹出层样式 */
.mapboxgl-popup {
  padding-bottom: 5px;
}
/* 控制关闭按钮 */
.mapboxgl-popup-close-button {
  /* display: none; */
}
.mapboxgl-popup-content {
  font: 400 15px/22px 'Source Sans Pro', 'Helvetica Neue', Sans-serif;
  padding: 0;
  width: 180px;
}
.mapboxgl-popup-content-wrapper {
  padding: 1%;
}
.mapboxgl-popup-content h3 {
  background: #91c949;
  color: #fff;
  margin: 0;
  display: block;
  padding: 10px;
  border-radius: 3px 3px 0 0;
  font-weight: 700;
  /* margin-top: -15px; */
}
.mapboxgl-popup-content h4 {
  margin: 0;
  display: block;
  padding: 10px;
  font-weight: 400;
}
.mapboxgl-popup-content div {
  padding: 10px;
}
.mapboxgl-container .leaflet-marker-icon {
  cursor: pointer;
}
.mapboxgl-popup-anchor-top > .mapboxgl-popup-content {
  margin-top: 15px;
}
.mapboxgl-popup-anchor-top > .mapboxgl-popup-tip {
  border-bottom-color: #91c949;
}
</style>
